package com.settlement.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.settlement.system.common.base.IBaseEnum;
import com.settlement.system.common.constant.SystemConstants;
import com.settlement.system.common.enums.LogRecordEnum;
import com.settlement.system.common.model.Option;
import com.settlement.system.common.util.DateUtils;
import com.settlement.system.common.util.StringUtils;
import com.settlement.system.handler.xxljob.XxlJobSampleHandler;
import com.settlement.system.mapper.SysLogRecordMapper;
import com.settlement.system.model.entity.SysLogRecord;
import com.settlement.system.model.entity.SysStore;
import com.settlement.system.model.form.SysLogRecordForm;
import com.settlement.system.model.query.SysLogRecordQuery;
import com.settlement.system.model.vo.SysLogRecordImportVo;
import com.settlement.system.service.SysDictService;
import com.settlement.system.service.SysLogRecordService;
import com.settlement.system.service.SysStoreService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 日志记录表 服务实现类
 * </p>
 *
 * @author huangrensen
 * @since 2024-06-20
 */
@Service
@RequiredArgsConstructor
public class SysLogRecordServiceImpl extends ServiceImpl<SysLogRecordMapper, SysLogRecord> implements SysLogRecordService {

    private final Logger logger = LoggerFactory.getLogger(SysLogRecordServiceImpl.class);
    private final SysStoreService storeService;

    private final SysDictService dictService;

    @Override
    public Page<SysLogRecord> getPage(SysLogRecordQuery queryParams) {
        // 查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        if (Objects.nonNull(queryParams.getCreateDate())) {
            queryParams.setStartTime(queryParams.getCreateDate().atStartOfDay());
            queryParams.setEndTime(queryParams.getCreateDate().plusDays(1).atStartOfDay());
        }
        // 查询数据
        Page<SysLogRecord> page = new Page<>(pageNum, pageSize);
        Page<SysLogRecord> mapperPage = this.baseMapper.getPage(page, queryParams);
        if (mapperPage.getRecords().size() > 0) {
            List<Option> platformOptionList = dictService.listDictOptions(SystemConstants.PLATFORM_KEY);
            SysStore sysStore;
            Option option;
            for (SysLogRecord record : mapperPage.getRecords()) {
                sysStore = storeService.getById(record.getStoreId());
                if (Objects.nonNull(sysStore)) {
                    record.setStoreName(sysStore.getCommercePlatformStoreName());
                    String platformKey = sysStore.getStoreKey();
                    option = platformOptionList.stream().filter(option1 -> option1.getValue().equals(platformKey)).findFirst().orElse(null);
                    if (Objects.nonNull(option)) {
                        record.setPlatformName(option.getLabel());
                    }
                }
            }
        }
        return mapperPage;
    }

    @Override
    public void saveSysLogRecord(SysLogRecordForm sysLogRecordForm) {
        Assert.notNull(sysLogRecordForm.getId(), "参数ID不能为空");
        SysLogRecord sysLogRecord = this.getById(sysLogRecordForm.getId());
        // 更新运行状态
        sysLogRecord.setResult(IBaseEnum.getLabelByValue(sysLogRecordForm.getResult(), LogRecordEnum.class));
        if(Objects.equals(sysLogRecord.getResult(), LogRecordEnum.SUCCESS.getLabel())){
            // 标记发送
            sysLogRecord.setSend(1);
        }
        // 周期
        sysLogRecord.setPeriod(sysLogRecordForm.getPeriod());
        // 开始执行时间
        sysLogRecord.setStartTime(DateUtils.convertStringToLocalDateTime(sysLogRecordForm.getStartTime()));
        // 下载文件名
        sysLogRecord.setFileName(sysLogRecordForm.getFileName());
        // 备注
        sysLogRecord.setRemark(sysLogRecordForm.getRemark());
        // 计算用时
        if(Objects.nonNull(sysLogRecordForm.getStartTime())){
            try{
                LocalDateTime time = DateUtils.convertStringToLocalDateTime(sysLogRecordForm.getStartTime());
                sysLogRecord.setCountTime("%s秒".formatted(Math.abs(Duration.between(time, LocalDateTime.now()).toSeconds())));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        sysLogRecord.cutString();
        this.saveOrUpdate(sysLogRecord);

    }

    @Override
    public SysLogRecordForm getSysLogRecordFormData(Long id) {
        SysLogRecord sysLogRecord = this.getById(id);
        SysLogRecordForm sysLogRecordForm = new SysLogRecordForm();
        BeanUtils.copyProperties(sysLogRecord, sysLogRecordForm);
        return sysLogRecordForm;
    }

    @Override
    public boolean deleteSysLogRecord(String ids) {
        Assert.isTrue(StringUtils.hasText(ids), "删除的数据为空");
        List<Long> idArray = Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList());
        return this.removeByIds(idArray);
    }

    @Override
    public void importData(List<SysLogRecordImportVo> voList) {
        List<SysLogRecord> sysLogRecordList = new ArrayList<>();
        for (SysLogRecordImportVo importVo : voList) {
            SysLogRecord sysLogRecord = new SysLogRecord();
            BeanUtils.copyProperties(importVo, sysLogRecord);
            sysLogRecordList.add(sysLogRecord);
        }
        this.saveOrUpdateBatch(sysLogRecordList);
    }

    @Override
    public List<SysLogRecordImportVo> findByIds(String idsStr) {
        if (!StringUtils.hasText(idsStr)) {
            return new ArrayList<>();
        }
        List<Long> ids = Arrays.stream(idsStr.split(",")).map(Long::parseLong).collect(Collectors.toList());
        List<SysLogRecord> sysLogRecordList = this.getBaseMapper().selectBatchIds(ids);
        List<SysLogRecordImportVo> voList = new ArrayList<>();
        for (SysLogRecord sysLogRecord : sysLogRecordList) {
            SysLogRecordImportVo vo = new SysLogRecordImportVo();
            BeanUtils.copyProperties(sysLogRecord, vo);
            voList.add(vo);
        }
        return voList;
    }

    @Override
    public boolean success(SysLogRecordForm sysLogRecordForm) {
        SysLogRecord sysLogRecord = this.getBaseMapper().selectById(sysLogRecordForm.getId());
        sysLogRecord.setResult(LogRecordEnum.SUCCESS.getLabel());
        sysLogRecord.setFileName(sysLogRecord.getFileName());
        return this.saveOrUpdate(sysLogRecord);
    }

    @Override
    public boolean checkCanRun(String storeCode, String orderType, String period) {
        SysStore sysStore = storeService.getByCode(storeCode);
        // 查看是否存在运行成功的记录
        List<SysLogRecord> logRecords = this.list(new LambdaQueryWrapper<SysLogRecord>().eq(SysLogRecord::getStoreId, sysStore.getId()).eq(SysLogRecord::getOrderType, orderType)
                .eq(SysLogRecord::getPeriod, period).eq(SysLogRecord::getResult, LogRecordEnum.SUCCESS.getLabel()));
        logger.info("检查当前任务是否运行成功：店铺【{}】账单类型【{}】周期【{}】，检查结果：【{}】", storeCode, orderType, period, logRecords.size() == 0);
        // 如果存在则不能运行
        return logRecords.size() == 0;
    }
}
